# [四] Spring 容器Bean的实例化
Spring 容器的初始化流程
上一节对Spring容器初始化的核心方法refresh()
中的obtainFreshBeanFactory()
方法流程已经全部分析完了,接下来进入refresh()
中的finishBeanFactoryInitialization()
方法,看看所有的单例bean是如何实例化的。
# Spring 初始化核心流程
spring容器初始化的核心方法
AbstractApplicationContext#refresh
,
├─
refresh Spring 初始化核心流程入口│ ├─
prepareRefresh ① 准备此上下文用于刷新,设置启动时间和active标志,初始化属性│ ├─
obtainFreshBeanFactory ② 创建 BeanFactory 已经跟踪过的源码流程│ ├─
prepareBeanFactory ③ 设置 BeanFactory 的基本属性│ ├─
postProcessBeanFactory ④ 子类处理自定义的BeanFactoryPostProcess│ ├─
invokeBeanFactoryPostProcessors ⑤ 调用所有的BeanFactoryPostProcessor│ ├─
registerBeanPostProcessors ⑥ 注册,把实现了BeanPostProcessor接口的类实例化,加到BeanFactory│ ├─
initMessageSource ⑦ 初始化上下文中的资源文件,如国际化文件的处理等│ ├─
initApplicationEventMulticaster ⑧ 初始化上下文的事件传播器│ ├─
onRefresh ⑨ 给子类扩展初始化其他Bean,springboot 中用来做内嵌 tomcat 启动│ ├─
registerListeners ⑩ 在所有bean中查找监听 bean,然后注册到广播器中│ ├─
finishBeanFactoryInitialization ⑪ 本节主要跟踪的源码流程│ └─
finishRefresh ⑫ 完成刷新过程,发布相应的事件
# ├─ finishBeanFactoryInitialization()
进入
finishBeanFactoryInitialization ()
方法类文件: org.springframework.context.support.
AbstractApplicationContext
/*
* TODO : 初始化所有的单例Bean(非延迟加载的),spring中最重要的方法之一
* 1、bean实例化过程
* 2、ioc
* 3、注解支持
* 4、BeanPostProcessor的执行
* 5、Aop的入口
*
* */
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
//设置类型转换器
// Initialize conversion service for this context.
if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
beanFactory.setConversionService(
beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
}
//暂时不要看
if (!beanFactory.hasEmbeddedValueResolver()) {
beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
}
//暂时不看
String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
for (String weaverAwareName : weaverAwareNames) {
getBean(weaverAwareName);
}
beanFactory.setTempClassLoader(null);
beanFactory.freezeConfiguration();
//重点看这个方法,重要程度:5
// Instantiate all remaining (non-lazy-init) singletons.
beanFactory.preInstantiateSingletons();
}
# ├─ preInstantiateSingletons()
进入
preInstantiateSingletons ()
方法类文件:org.springframework.beans.factory.support.
DefaultListableBeanFactory
/**
* TODO : 实例化单例bean前的预处理
*/
public void preInstantiateSingletons() throws BeansException {
if (logger.isTraceEnabled()) {
logger.trace("Pre-instantiating singletons in " + this);
}
//同xml解析时,把所有beanName都缓存到beanDefinitionNames了
List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);
// Trigger initialization of all non-lazy singleton beans...
for (String beanName : beanNames) {
//把父BeanDefinition里面的属性拿到子BeanDefinition中
RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
//如果不是抽象的,单例的,非懒加载的就实例化
if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
//判断bean是否实现了FactoryBean接口,这里可以不看
if (isFactoryBean(beanName)) {
Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
if (bean instanceof FactoryBean) {
final FactoryBean<?> factory = (FactoryBean<?>) bean;
boolean isEagerInit;
if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
isEagerInit = AccessController.doPrivileged((PrivilegedAction<Boolean>)
((SmartFactoryBean<?>) factory)::isEagerInit,
getAccessControlContext());
}
else {
isEagerInit = (factory instanceof SmartFactoryBean &&
((SmartFactoryBean<?>) factory).isEagerInit());
}
if (isEagerInit) {
getBean(beanName);
}
}
}
else {
//主要从这里进入,看看实例化过程
getBean(beanName);
}
}
}
//省略无关代码
...
}
知识点
bean实例化的条件
- 非抽象类的
- 单例的
- 非延迟加载的
# ├─ getBean()
进入
getBean()
方法类文件:org.springframework.beans.factory.support.
AbstractBeanFactory
public Object getBean(String name) throws BeansException {
// 最核心的业务方法
return doGetBean(name, null, null, false);
}
# ├─ doGetBean()
进入
doGetBean()
方法类文件:org.springframework.beans.factory.support.
AbstractBeanFactory
/**
* TODO : 获取bean的核心方法
*/
protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType,
@Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {
// 获取一个beanName,处理两种情况,一个是前面说的 FactoryBean (前面带 '&'),
// 一个是别名问题,因为这个方法是 getBean,获取 Bean 用的,你要是传一个别名进来,是完全可以的
final String beanName = transformedBeanName(name);
Object bean;
/**
* TODO : 检查缓存中或者实例工厂中是否有对应的实例
* 因为在创建单例 bean的时候会存在依赖注入,而在创建依赖的时候为了避免循环依赖,
* spring创建bean的原则是:不等 bean 创建完成就将创建bean的 ObjectFactory 提早曝光,
* 换句话说,也就是将 ObjectFactory 加入到缓存中,一旦下一个bean创建的时候需要依赖上
* 一个bean则直接使用 ObjectFactory
*/
Object sharedInstance = getSingleton(beanName);
//如果缓存里面能拿到实例
if (sharedInstance != null && args == null) {
if (logger.isTraceEnabled()) {
if (isSingletonCurrentlyInCreation(beanName)) {
logger.trace("Returning eagerly cached instance of singleton bean '" + beanName +
"' that is not fully initialized yet - a consequence of a circular reference");
}
else {
logger.trace("Returning cached instance of singleton bean '" + beanName + "'");
}
}
// 该方法是 FactoryBean 接口的调用入口
// 如果是普通 Bean 的话,直接返回 sharedInstance(直接返回对象本身)
// 如果是 FactoryBean 的话,返回它创建的那个实例对象(返回指定方法返回的实例)
bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
}
else {
/**
* TOTO : 处理原型模式下循环依赖的问题
* --触发场景:原型模式下,如果存在A中有B属性,B中有A属性,那么当依赖注入的时候,
* 就会产生当A还没创建完的时候,由于对B的创建再次返回创建A,造成循环依赖
*
* 如果 singletonObjects 缓存里面没有,则走下来
* 如果是 scope 是 Prototype 的,校验是否有出现循环依赖,如果有则直接报错
*/
if (isPrototypeCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}
// Check if bean definition exists in this factory.
// 检查一下这个 BeanDefinition 在容器中是否存在
BeanFactory parentBeanFactory = getParentBeanFactory();
// 如果不存在 beanDefinitionMap (一个concurrenthashmap)容器中,也就是所有已经
// 加载的类中不包括beanName,则尝试从 parentBeanFactory 中检测
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
// Not found -> check parent.
// 如果当前容器不存在这个 BeanDefinition,试试父容器中有没有
String nameToLookup = originalBeanName(name);
if (parentBeanFactory instanceof AbstractBeanFactory) {
return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
nameToLookup, requiredType, args, typeCheckOnly);
}
else if (args != null) {
// Delegation to parent with explicit args.
// 使用显式参数委托给父进程。
return (T) parentBeanFactory.getBean(nameToLookup, args);
}
else if (requiredType != null) {
// No args -> delegate to standard getBean method.
// 没有 args -> 委托给标准的 getBean 方法
return parentBeanFactory.getBean(nameToLookup, requiredType);
}
else {
return (T) parentBeanFactory.getBean(nameToLookup);
}
}
// typeCheckOnly 为 false,将当前 beanName 放入一个 alreadyCreated 的 Set 集合中。
// 如果不是仅仅做类型检查而是创建bean,则进行记录
if (!typeCheckOnly) {
markBeanAsCreated(beanName);
}
/*
* 总结:
* 到这里的话,要准备创建 Bean 了,对于 singleton 的 Bean 来说,容器中还没创建过此 Bean;
* 对于 prototype 的 Bean 来说,本来就是要创建一个新的 Bean。
*/
try {
/**
* TODO : 合并父类的相关属性
* -- 将存储XML的 GenericBeanDefinition 转换为 RootBeanDefinition,如果指定
* beanName 是子类bean的话,同时合并父类的相关属性
*/
final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
checkMergedBeanDefinition(mbd, beanName, args);
//获取依赖对象属性,依赖对象要先实例化
// Guarantee initialization of beans that the current bean depends on.
// 先初始化依赖的所有 Bean,这个很好理解。
// 注意,这里的依赖指的是 depends-on 中定义的依赖
String[] dependsOn = mbd.getDependsOn();
// 如果存在依赖则递归实例化依赖的bean
if (dependsOn != null) {
for (String dep : dependsOn) {
// 检查是不是有循环依赖,这里的循环依赖和我们前面说的循环依赖又不一样,
// 这里肯定是不允许出现的
if (isDependent(beanName, dep)) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
}
// 注册一下依赖关系,缓存依赖调用
registerDependentBean(dep, beanName);
try {
//实例化
getBean(dep);
}
catch (NoSuchBeanDefinitionException ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"'" + beanName + "' depends on missing bean '" + dep + "'", ex);
}
}
}
//着重看,大部分是单例的情况
// Create bean instance.
// 实例化完依赖的bean后,便可以实例化 mbd 引用对象本身了
// 如果是 singleton scope 的,创建 singleton 的实例
if (mbd.isSingleton()) {
sharedInstance = getSingleton(beanName, () -> {
try {
// 执行创建 Bean
return createBean(beanName, mbd, args);
}
catch (BeansException ex) {
// 从单例缓存中显式删除实例:它可能已经被放在那里了
// 急切被创建进程,以允许循环引用解析。
// 还要删除接收到该bean的临时引用的所有bean。
destroySingleton(beanName);
throw ex;
}
});
// 该方法是FactoryBean接口的调用入口
bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}
// 如果是 prototype scope 的,创建 prototype 的实例
else if (mbd.isPrototype()) {
// It's a prototype -> create a new instance.
Object prototypeInstance = null;
try {
beforePrototypeCreation(beanName);
prototypeInstance = createBean(beanName, mbd, args);
}
finally {
afterPrototypeCreation(beanName);
}
// 该方法是 FactoryBean 接口的调用入口
bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
}
// 如果不是 singleton 和 prototype 的话,需要委托给相应的实现类来处理
else {
String scopeName = mbd.getScope();
final Scope scope = this.scopes.get(scopeName);
if (scope == null) {
throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
}
try {
Object scopedInstance = scope.get(beanName, () -> {
beforePrototypeCreation(beanName);
try {
// 执行创建 Bean
return createBean(beanName, mbd, args);
}
finally {
afterPrototypeCreation(beanName);
}
});
// 该方法是FactoryBean接口的调用入口
bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
}
catch (IllegalStateException ex) {
throw new BeanCreationException(beanName,
"Scope '" + scopeName + "' is not active for the current thread; consider " +
"defining a scoped proxy for this bean if you intend to refer to it from a singleton",
ex);
}
}
}
catch (BeansException ex) {
cleanupAfterBeanCreationFailure(beanName);
throw ex;
}
}
// 最后,检查一下类型对不对,不对的话就抛异常,对的话就返回
if (requiredType != null && !requiredType.isInstance(bean)) {
try {
T convertedBean = getTypeConverter().convertIfNecessary(bean, requiredType);
if (convertedBean == null) {
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
}
return convertedBean;
}
catch (TypeMismatchException ex) {
if (logger.isTraceEnabled()) {
logger.trace("Failed to convert bean '" + name + "' to required type '" +
ClassUtils.getQualifiedName(requiredType) + "'", ex);
}
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
}
}
return (T) bean;
}
# │ ├─ getSingleton()
进入
getSingleton()
方法类文件:org.springframework.beans.factory.support.
DefaultSingletonBeanRegistry
/**
* TODO : 获取单例bean
*/
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
//根据beanName从缓存中拿实例
//先从一级缓存拿
Object singletonObject = this.singletonObjects.get(beanName);
//如果bean还正在创建,还没创建完成,其实就是堆内存有了,属性还没有DI依赖注入
if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
synchronized (this.singletonObjects) {
//从二级缓存中拿
singletonObject = this.earlySingletonObjects.get(beanName);
//如果还拿不到,并且允许bean提前暴露
if (singletonObject == null && allowEarlyReference) {
//从三级缓存中拿到对象工厂
ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
if (singletonFactory != null) {
//从工厂中拿到对象
singletonObject = singletonFactory.getObject();
//升级到二级缓存
this.earlySingletonObjects.put(beanName, singletonObject);
//删除三级缓存
this.singletonFactories.remove(beanName);
}
}
}
}
return singletonObject;
}
知识点
Spring容器中的三级缓存,是为了解决Spring 循环依赖
的问题。保存在三级缓存中的bean不是完整的bean实例,因为Spring创建bean的原则是:不等 bean 创建完成就将创建bean的 ObjectFactory 提早曝光
,所以只有完整的bean实例才会最终放到一级缓存中
。
# │ └─ getSingleton()
由于第一次进来缓存肯定为空,进入else条件里的
getSingleton()
方法类文件:org.springframework.beans.factory.support.
DefaultSingletonBeanRegistry
/**
* TODO : 获取单例bean
*/
public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
Assert.notNull(beanName, "Bean name must not be null");
synchronized (this.singletonObjects) {
//如果缓存中有,则直接返回
Object singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
if (this.singletonsCurrentlyInDestruction) {
throw new BeanCreationNotAllowedException(beanName,
"Singleton bean creation not allowed while singletons of this factory are in destruction " +
"(Do not request a bean from a BeanFactory in a destroy method implementation!)");
}
if (logger.isDebugEnabled()) {
logger.debug("Creating shared instance of singleton bean '" + beanName + "'");
}
// 把 beanName 添加到 singletonsCurrentlyInCreation Set容器中,
// 在这个集合里面的 bean都是正在实例化的 bean
beforeSingletonCreation(beanName);
boolean newSingleton = false;
boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
if (recordSuppressedExceptions) {
this.suppressedExceptions = new LinkedHashSet<>();
}
try {
singletonObject = singletonFactory.getObject();
newSingleton = true;
}
catch (IllegalStateException ex) {
// Has the singleton object implicitly appeared in the meantime ->
// if yes, proceed with it since the exception indicates that state.
singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
throw ex;
}
}
catch (BeanCreationException ex) {
if (recordSuppressedExceptions) {
for (Exception suppressedException : this.suppressedExceptions) {
ex.addRelatedCause(suppressedException);
}
}
throw ex;
}
finally {
if (recordSuppressedExceptions) {
this.suppressedExceptions = null;
}
// bean创建完成后,从singletonsCurrentlyInCreation删除该bean
afterSingletonCreation(beanName);
}
if (newSingleton) {
// 创建对象成功时,把对象缓存到 singletonObjects缓存中,
// bean创建完成时放入一级缓存
addSingleton(beanName, singletonObject);
}
}
return singletonObject;
}
}
# │ │ ├─ beforeSingletonCreation()
进入
beforeSingletonCreation()
方法类文件:org.springframework.beans.factory.support.
DefaultSingletonBeanRegistry
/**
* TODO : 把beanName添加到singletonsCurrentlyInCreation (Set)容器中
*/
protected void beforeSingletonCreation(String beanName) {
// 在这个集合里面的bean都是正在实例化的bean,标识作用
if (!this.inCreationCheckExclusions.contains(beanName) && !this.singletonsCurrentlyInCreation.add(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}
}
知识点
singletonsCurrentlyInCreation
(正在创建中的bean),可以理解为当前bean只是在JVM的堆内存中分配了地址,但是相关依赖属性并没有添加进来。
# │ │ ├─ createBean()
接下来会调用
singletonFactory.getObject()
方法,而getObject()
会调用外层Lambda
表达式中实现getObject()
的 业务方法,即createBean()
方法进入
createBean()
方法类文件:org.springframework.beans.factory.support.
AbstractAutowireCapableBeanFactory
/**
* TODO : 创建bean,过渡方法
*/
protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException {
if (logger.isTraceEnabled()) {
logger.trace("Creating instance of bean '" + beanName + "'");
}
RootBeanDefinition mbdToUse = mbd;
Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
mbdToUse = new RootBeanDefinition(mbd);
mbdToUse.setBeanClass(resolvedClass);
}
try {
// 处理同名方法是否只有一个,有则进行标识,方便后面处理
mbdToUse.prepareMethodOverrides();
}
catch (BeanDefinitionValidationException ex) {
throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
beanName, "Validation of method overrides failed", ex);
}
try {
/**
* TargetSource接口的运用,可以在用改一个类实现该接口,然后在里面定义实例化对象的方式,然后返回
* 也就是说不需要spring帮助我们实例化对象
* 这里可以直接返回实例本身
* 这个代码不用看,实际开发过程中用不到,我会做为一个甜点分享
*/
Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
if (bean != null) {
return bean;
}
}
catch (Throwable ex) {
throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
"BeanPostProcessor before instantiation of bean failed", ex);
}
try {
//主要看这个方法,重要程度 5
Object beanInstance = doCreateBean(beanName, mbdToUse, args);
if (logger.isTraceEnabled()) {
logger.trace("Finished creating instance of bean '" + beanName + "'");
}
return beanInstance;
}
catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {
throw ex;
}
catch (Throwable ex) {
throw new BeanCreationException(
mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);
}
}
# │ │ └─ doCreateBean()
进入
doCreateBean()
核心方法类文件:org.springframework.beans.factory.support.
AbstractAutowireCapableBeanFactory
/**
* TODO : 创建bean实例的核心方法
*/
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
throws BeanCreationException {
// 封装bean的实例
BeanWrapper instanceWrapper = null;
if (mbd.isSingleton()) {
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
if (instanceWrapper == null) {
//创建实例,,重点看,重要程度:5
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
final Object bean = instanceWrapper.getWrappedInstance();
Class<?> beanType = instanceWrapper.getWrappedClass();
if (beanType != NullBean.class) {
mbd.resolvedTargetType = beanType;
}
// Allow post-processors to modify the merged bean definition.
synchronized (mbd.postProcessingLock) {
if (!mbd.postProcessed) {
try {
//CommonAnnotationBeanPostProcessor 支持了@PostConstruct,@PreDestroy,@Resource注解
//AutowiredAnnotationBeanPostProcessor 支持 @Autowired,@Value注解
//BeanPostProcessor接口的典型运用,这里要理解这个接口
//对类中注解的装配过程
//重要程度5,必须看
applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
}
catch (Throwable ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Post-processing of merged bean definition failed", ex);
}
mbd.postProcessed = true;
}
}
// 是否单例 bean 提前暴露
boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
isSingletonCurrentlyInCreation(beanName));
if (earlySingletonExposure) {
if (logger.isTraceEnabled()) {
logger.trace("Eagerly caching bean '" + beanName +
"' to allow for resolving potential circular references");
}
//这里着重理解,对理解循环依赖帮助非常大,重要程度 5 添加三级缓存
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
}
// Initialize the bean instance.
Object exposedObject = bean;
try {
//ioc di,依赖注入的核心方法,该方法必须看,重要程度:5
populateBean(beanName, mbd, instanceWrapper);
//bean 实例化+ioc依赖注入完以后的调用,非常重要,重要程度:5
exposedObject = initializeBean(beanName, exposedObject, mbd);
}
catch (Throwable ex) {
if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
throw (BeanCreationException) ex;
}
else {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
}
}
if (earlySingletonExposure) {
Object earlySingletonReference = getSingleton(beanName, false);
if (earlySingletonReference != null) {
if (exposedObject == bean) {
exposedObject = earlySingletonReference;
}
else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
String[] dependentBeans = getDependentBeans(beanName);
Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
for (String dependentBean : dependentBeans) {
if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
actualDependentBeans.add(dependentBean);
}
}
if (!actualDependentBeans.isEmpty()) {
throw new BeanCurrentlyInCreationException(beanName,
"Bean with name '" + beanName + "' has been injected into other beans [" +
StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
"] in its raw version as part of a circular reference, but has eventually been " +
"wrapped. This means that said other beans do not use the final version of the " +
"bean. This is often the result of over-eager type matching - consider using " +
"'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.");
}
}
}
}
// Register bean as disposable.
try {
//注册bean销毁时的类DisposableBeanAdapter
registerDisposableBeanIfNecessary(beanName, bean, mbd);
}
catch (BeanDefinitionValidationException ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
}
return exposedObject;
}
# │ │ │ ├─ createBeanInstance()
进入
createBeanInstance()
核心方法类文件:org.springframework.beans.factory.support.
AbstractAutowireCapableBeanFactory
/**
* TODO : 把创建bean实例
*/
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
// Make sure bean class is actually resolved at this point.
//反射拿到Class对象
Class<?> beanClass = resolveBeanClass(mbd, beanName);
if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Bean class isn't public, and non-public access not allowed: " + beanClass.getName());
}
Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
if (instanceSupplier != null) {
return obtainFromSupplier(instanceSupplier, beanName);
}
//如果有FactoryMethodName属性
if (mbd.getFactoryMethodName() != null) {
// 反射的方式调用FactoryMethod
return instantiateUsingFactoryMethod(beanName, mbd, args);
}
// Shortcut when re-creating the same bean...
boolean resolved = false;
boolean autowireNecessary = false;
if (args == null) {
synchronized (mbd.constructorArgumentLock) {
if (mbd.resolvedConstructorOrFactoryMethod != null) {
resolved = true;
autowireNecessary = mbd.constructorArgumentsResolved;
}
}
}
if (resolved) {
if (autowireNecessary) {
return autowireConstructor(beanName, mbd, null, null);
}
else {
return instantiateBean(beanName, mbd);
}
}
// 寻找当前正在实例化的bean中有@Autowired注解的构造函数
Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
// 如果ctors不为空,就说明构造函数上有@Autowired注解,
// 接下来解析构造函数里的参数
return autowireConstructor(beanName, mbd, ctors, args);
}
// Preferred constructors for default construction?
ctors = mbd.getPreferredConstructors();
if (ctors != null) {
return autowireConstructor(beanName, mbd, ctors, null);
}
//无参构造函数的实例化,大部分的实例是采用的无参构造函数的方式实例化
return instantiateBean(beanName, mbd);
}
进入 determineConstructorsFromBeanPostProcessors() 方法
类文件:org.springframework.beans.factory.support.
AbstractAutowireCapableBeanFactory
/**
* TODO : 返回前正在实例化的bean中有@Autowired注解的构造函数
*/
protected Constructor<?>[] determineConstructorsFromBeanPostProcessors(@Nullable Class<?> beanClass, String beanName)
throws BeansException {
if (beanClass != null && hasInstantiationAwareBeanPostProcessors()) {
// 拿到 BeanPostProcessor 的所有接口,遍历
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
// 获取到有@Autowired注解信息的构造函数
Constructor<?>[] ctors = ibp.determineCandidateConstructors(beanClass, beanName);
if (ctors != null) {
return ctors;
}
}
}
}
return null;
}
知识点
getBeanPostProcessors()
方法,获取所有BeanPostProcessor
接口,是AbstractBeanFactory
类中的一个List<BeanPostProcessor> beanPostProcessors = new CopyOnWriteArrayList<>()
容器,装载了上下文中所有的BeanPostProcessor
类的实例。SmartInstantiationAwareBeanPostProcessor
类中的determineCandidateConstructors
方法,会调用其子类AutowiredAnnotationBeanPostProcessor
中的determineCandidateConstructors
方法,来获取到有@Autowired
注解信息的构造函数。AutowiredAnnotationBeanPostProcessor
类会完成@Autowired
和@value
两个注解的扫描。
返回到
createBeanInstance()
方法,进入autowireConstructor()
方法
autowireConstructor()
方法直接调用了ConstructorResolver
类的autowireConstructor()
,不重要跳过类文件:org.springframework.beans.factory.support.
ConstructorResolver
知识点
ConstructorResolver
类的autowireConstructor()
,用来解析构造函数中的参数,最终解析的本质是通过beanFactory.getBean()
方法,将参数中引用的类实例化
。
# │ │ │ ├─ applyMergedBean..()
进入
applyMergedBeanDefinitionPostProcessors()
核心方法类文件:org.springframework.beans.factory.support.
AbstractAutowireCapableBeanFactory
/**
* TODO : 对类中注解的装配收集过程
*/
protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd, Class<?> beanType, String beanName) {
// 获取所有 BeanPostProcessor 类
// getBeanPostProcessors() (List<BeanPostProcessor> beanPostProcessors)
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof MergedBeanDefinitionPostProcessor) {
MergedBeanDefinitionPostProcessor bdp = (MergedBeanDefinitionPostProcessor) bp;
// 收集注解信息,最终存放到 InjectionMetadata 类中,不用看
bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName);
}
}
}
知识点
注解的装配收集过程,由BeanPostProcessor
类来处理:
首先会从List<BeanPostProcessor> beanPostProcessors
即getBeanPostProcessors()方法
的集合中拿到所有实现了BeanPostProcessor
接口的实现类,然后通过反射
拿到实现类里所有属性,然后开始收集注解信息,主要由以下几个注解类处理:
CommonAnnotationBeanPostProcessor
:处理@Resource 注解的解析。InitDestroyAnnotationBeanPostProcessor
:处理@PostConstruct、@PreDestroy 注解的解析。AutowiredAnnotationBeanPostProcessor
:处理@Autowired、@Value、@Inject(JSR-330的注解,功能和使用方法与@Autowired相同)注解的解析。RequiredAnnotationBeanPostProcessor
:处理@Required注解的解析。
接下来循环遍历包含注解元素的类以及父类,如果解析到属性上有指定注解的类(clazz)
,则将对应的属性元素(Field或者Method)添加到一个List<InjectionMetadata.InjectedElement> elements
中,然后返回new InjectionMetadata(clazz, elements)
,最后把返回的InjectionMetadata
放到Map<String, InjectionMetadata> injectionMetadataCache = new ConcurrentHashMap<>(256)
缓存中去,至此注解的装配收集过程全部完成。
这些注解类会调用
findResourceMetadata()
方法中的buildResourceMetadata()
方法,执行封装处理。进入
buildResourceMetadata()
方法类文件:org.springframework.beans.factory.annotation.
AutowiredAnnotationBeanPostProcessor
/**
* TODO : 注解信息存放到 InjectionMetadata 类的具体过程
*/
private InjectionMetadata buildResourceMetadata(final Class<?> clazz) {
// 标记有 @Autowired @Value等注解的元素集合( Field和 Method )
List<InjectionMetadata.InjectedElement> elements = new ArrayList<>();
// 标记有 @Autowired @Value等注解的类
Class<?> targetClass = clazz;
do {
final List<InjectionMetadata.InjectedElement> currElements = new ArrayList<>();
ReflectionUtils.doWithLocalFields(targetClass, field -> {
if (webServiceRefClass != null && field.isAnnotationPresent(webServiceRefClass)) {
if (Modifier.isStatic(field.getModifiers())) {
throw new IllegalStateException("@WebServiceRef annotation is not supported on static fields");
}
currElements.add(new WebServiceRefElement(field, field, null));
}
// ...... 省略不重要的业务方法
elements.addAll(0, currElements);
targetClass = targetClass.getSuperclass();
}
// 除了扫描自己类的@Autowired等注解,还会扫描父类是否有注解
while (targetClass != null && targetClass != Object.class);
// 用这个class和list 作为参数封装成一个InjectionMetadata对象返回
return new InjectionMetadata(clazz, elements);
}
# │ │ │ ├─ addSingletonFactory()
进入
addSingletonFactory()
方法类文件:org.springframework.beans.factory.support.
DefaultSingletonBeanRegistry
/**
* TODO : 循环依赖的解决方案,添加到三级缓存
*/
protected void addSingletonFactory(String beanName, ObjectFactory<?> singletonFactory) {
Assert.notNull(singletonFactory, "Singleton factory must not be null");
synchronized (this.singletonObjects) {
if (!this.singletonObjects.containsKey(beanName)) {
this.singletonFactories.put(beanName, singletonFactory);
this.earlySingletonObjects.remove(beanName);
this.registeredSingletons.add(beanName);
}
}
}
# │ │ │ ├─ populateBean()
进入
populateBean()
核心方法,依赖注入的核心方法类文件:org.springframework.beans.factory.support.
AbstractAutowireCapableBeanFactory
/**
* TODO : Spring IOC DI,依赖注入的核心方法
*/
protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
if (bw == null) {
if (mbd.hasPropertyValues()) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
}
else {
return;
}
}
boolean continueWithPropertyPopulation = true;
//这里很有意思,写接口可以让所有类都不能依赖注入
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
//是否需要DI,依赖注入
continueWithPropertyPopulation = false;
break;
}
}
}
}
if (!continueWithPropertyPopulation) {
return;
}
PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);
if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_NAME || mbd.getResolvedAutowireMode() == AUTOWIRE_BY_TYPE) {
MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_NAME) {
autowireByName(beanName, mbd, bw, newPvs);
}
if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_TYPE) {
autowireByType(beanName, mbd, bw, newPvs);
}
pvs = newPvs;
}
boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);
PropertyDescriptor[] filteredPds = null;
//重点看这个if代码块,重要程度 5
if (hasInstAwareBpps) {
if (pvs == null) {
pvs = mbd.getPropertyValues();
}
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
//依赖注入过程,@Autowired的支持
PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
if (pvsToUse == null) {
if (filteredPds == null) {
filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
}
//老版本用这个完成依赖注入过程,@Autowired的支持
pvsToUse = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
if (pvsToUse == null) {
return;
}
}
pvs = pvsToUse;
}
}
}
if (needsDepCheck) {
if (filteredPds == null) {
filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
}
checkDependencies(beanName, mbd, filteredPds, pvs);
}
//这个方法很鸡肋了,建议不看,是老版本用<property name="username" value="Jack"/>
//标签做依赖注入的代码实现,复杂且无用
if (pvs != null) {
applyPropertyValues(beanName, mbd, bw, pvs);
}
}
知识点
- 如果依赖注入的构造函数中参数是
引用类型
,那么一定会触发getBean()
方法进行引用类型的实例化。
进入
postProcessProperties()
方法,该方法为钩子方法,进入
AutowiredAnnotationBeanPostProcessor
类实现的postProcessProperties()
类文件:org.springframework.beans.factory.annotation.
AutowiredAnnotationBeanPostProcessor
/**
* TODO : 过渡方法,重点看 inject()方法
*/
public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) {
// 拿到存在InjectionMetadata 对象
InjectionMetadata metadata = findAutowiringMetadata(beanName, bean.getClass(), pvs);
try {
// 依赖注入调用核心方法
metadata.inject(bean, beanName, pvs);
}
catch (BeanCreationException ex) {
throw ex;
}
catch (Throwable ex) {
throw new BeanCreationException(beanName, "Injection of autowired dependencies failed", ex);
}
return pvs;
}
进入
inject()
方法;类文件:org.springframework.beans.factory.annotation.
InjectionMetadata
/**
* TODO : 循环调用有注解依赖的元素的方法
*/
public void inject(Object target, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {
// 收集到有注解的方法和属性集合
Collection<InjectedElement> checkedElements = this.checkedElements;
Collection<InjectedElement> elementsToIterate =
(checkedElements != null ? checkedElements : this.injectedElements);
if (!elementsToIterate.isEmpty()) {
// 循环调用里面InjectedElement的inject注入方法
for (InjectedElement element : elementsToIterate) {
if (logger.isTraceEnabled()) {
logger.trace("Processing injected element of bean '" + beanName + "': " + element);
}
element.inject(target, beanName, pvs);
}
}
}
进入子类的
inject()
方法,该方法为钩子方法,类文件:org.springframework.beans.factory.annotation.
AutowiredAnnotationBeanPostProcessor
/**
* TODO : inject 依赖注入的最终反射实现
*/
protected void inject(Object bean, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {
Field field = (Field) this.member;
Object value;
if (this.cached) {
value = resolvedCachedArgument(beanName, this.cachedFieldValue);
}
else {
DependencyDescriptor desc = new DependencyDescriptor(field, this.required);
desc.setContainingClass(bean.getClass());
Set<String> autowiredBeanNames = new LinkedHashSet<>(1);
Assert.state(beanFactory != null, "No BeanFactory available");
TypeConverter typeConverter = beanFactory.getTypeConverter();
try {
value = beanFactory.resolveDependency(desc, beanName, autowiredBeanNames, typeConverter);
}
catch (BeansException ex) {
throw new UnsatisfiedDependencyException(null, beanName, new InjectionPoint(field), ex);
}
synchronized (this) {
if (!this.cached) {
if (value != null || this.required) {
this.cachedFieldValue = desc;
registerDependentBeans(beanName, autowiredBeanNames);
if (autowiredBeanNames.size() == 1) {
String autowiredBeanName = autowiredBeanNames.iterator().next();
if (beanFactory.containsBean(autowiredBeanName) &&
beanFactory.isTypeMatch(autowiredBeanName, field.getType())) {
this.cachedFieldValue = new ShortcutDependencyDescriptor(
desc, autowiredBeanName, field.getType());
}
}
}
else {
this.cachedFieldValue = null;
}
this.cached = true;
}
}
}
if (value != null) {
ReflectionUtils.makeAccessible(field);
// 最终field的依赖注入通过反射实现
// method的依赖注入通过method.invoke(bean, arguments)实现
//
field.set(bean, value);
}
}
}
知识点
依赖注入
的过程,拿到收集到的方法和属性的集合,field属性
和method方法
分别通过AutowiredAnnotationBeanPostProcessor
的内部类AutowiredFieldElement.inject()
方法 和AutowiredMethodElement.inject()
方法,通过反射的方式最后完成依赖注入。
# │ │ │ ├─ initializeBean()
进入
initializeBean()
方法,类文件:org.springframework.beans.factory.support.
AbstractAutowireCapableBeanFactory
/**
* TODO : bean 实例化+ioc依赖注入完以后的调用,非常重要,重要程度:5
*/
protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
invokeAwareMethods(beanName, bean);
return null;
}, getAccessControlContext());
}
else {
//调用Aware方法
invokeAwareMethods(beanName, bean);
}
Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {
//对类中某些特殊方法的调用,比如@PostConstruct,Aware接口,非常重要 重要程度 :5
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
}
try {
//InitializingBean接口,afterPropertiesSet,init-method属性调用,非常重要,重要程度:5
invokeInitMethods(beanName, wrappedBean, mbd);
}
catch (Throwable ex) {
throw new BeanCreationException(
(mbd != null ? mbd.getResourceDescription() : null),
beanName, "Invocation of init method failed", ex);
}
if (mbd == null || !mbd.isSynthetic()) {
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
return wrappedBean;
}
进入
applyBeanPostProcessorsBeforeInitialization()
方法,类文件:org.springframework.beans.factory.support.
AbstractAutowireCapableBeanFactory
/**
* TODO : 初始化之前对BeanPostProcessor的处理
*/
public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
/*
* 着重看几个
* 1、ApplicationContextAwareProcessor 对某个Aware接口方法的调用
* 2、InitDestroyAnnotationBeanPostProcessor @PostConstruct注解方法的调用
* 3、ImportAwareBeanPostProcessor 对ImportAware类型实例setImportMetadata调用
* 这个对理解springboot有很大帮助。 这里暂时不需要深入看
* */
for (BeanPostProcessor processor : getBeanPostProcessors()) {
Object current = processor.postProcessBeforeInitialization(result, beanName);
if (current == null) {
return result;
}
result = current;
}
return result;
}
执行完返回一个 Oject对象,进入` invokeInitMethods() ``方法,
类文件:org.springframework.beans.factory.support.
AbstractAutowireCapableBeanFactory
/**
* TODO : 指定初始化方法
*/
protected void invokeInitMethods(String beanName, final Object bean, @Nullable RootBeanDefinition mbd)
throws Throwable {
// 如果当前 bean 是 InitializingBean 的实例
boolean isInitializingBean = (bean instanceof InitializingBean);
if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
if (logger.isTraceEnabled()) {
logger.trace("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
}
if (System.getSecurityManager() != null) {
try {
AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> {
((InitializingBean) bean).afterPropertiesSet();
return null;
}, getAccessControlContext());
}
catch (PrivilegedActionException pae) {
throw pae.getException();
}
}
else {
// 直接调用afterPropertiesSet方法
((InitializingBean) bean).afterPropertiesSet();
}
}
if (mbd != null && bean.getClass() != NullBean.class) {
String initMethodName = mbd.getInitMethodName();
if (StringUtils.hasLength(initMethodName) &&
!(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
!mbd.isExternallyManagedInitMethod(initMethodName)) {
// 反射调用 initMethod 方法
// initMethod.invoke(bean)
invokeCustomInitMethod(beanName, bean, mbd);
}
}
}
知识点
InitializingBean
接口的特点:
- 如果需要在一个类实例化以后去做一些事情,那么可以实现
InitializingBean
接口;常用的比如Redis缓存预热、Eureka注册中心的注册、Dubbo注册中心的注册、Mybatis里的xml解析等也是通过实现InitializingBean
接口来完成的。BeanNameAware
接口的特点: - 获取bean名称,实现
BeanNameAware
接口,可以通过setBeanName(Stringname
),得到子类的bean名称。
# │ │ │ └─ registerDisposableBean..()
进入
registerDisposableBeanIfNecessary()
方法,类文件:org.springframework.beans.factory.support.
AbstractBeanFactory
/**
* TODO : 注册bean销毁时的类 DisposableBeanAdapter
*/
protected void registerDisposableBeanIfNecessary(String beanName, Object bean, RootBeanDefinition mbd) {
AccessControlContext acc = (System.getSecurityManager() != null ? getAccessControlContext() : null);
if (!mbd.isPrototype() && requiresDestruction(bean, mbd)) {
if (mbd.isSingleton()) {
registerDisposableBean(beanName,
new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
}
else {
// A bean with a custom scope...
Scope scope = this.scopes.get(mbd.getScope());
if (scope == null) {
throw new IllegalStateException("No Scope registered for scope name '" + mbd.getScope() + "'");
}
scope.registerDestructionCallback(beanName,
new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
}
}
}
到此为止,Spring的实例化和依赖注入、初始化的流程都执行完毕。